import {onMounted} from "vue";
import appStore from '../store/index';
import {useRouter} from 'vue-router';
import {getToken,login} from '@/api/sys'

export default function qywxAuth() {
    /**
     * 判断是否过期
     */
    const isExpiration = () => {
        let tokenExpiration = localStorage.getItem("tokenExpiration") || 0;
        return Number(tokenExpiration) < Date.now()
    }
    // 页面加载时候执行
    onMounted(async () => {
        const router = useRouter();
        // 1.判断vuex是否有token信息 以及token是否过期
        let uerId = localStorage.getItem("uerId") || null;

        if (uerId == null || uerId == "" || isExpiration()) {
            const params = new URLSearchParams(window.location.search)
            // 2.1 因为token无效，所以重新获取，判断url中是否有code值
            const code = params.get('code')
            if (code == null || code == "") {
                return router.push({name: "login"})
            }
            // 2.2 根据code重新获取token值
            let token;
            await getToken({code: code}).then((rsp) => {
                //登录
                let user = {
                    id: rsp.data.userId,
                    name: rsp.data.userName,
                    avatar: rsp.data.avatar,
                    position: rsp.data.position,
                    type: 'user',
                }
                selectInstance.roles = rsp.data.roles[0].replace(/\"/g, "")
                localStorage.setItem('roles', JSON.stringify(selectInstance.roles))
                // this.$store.state.loginUser = user
                localStorage.setItem('loginUser', JSON.stringify(user))
                localStorage.setItem('wflow-token', rsp.data.token)
                selectInstance.processVisible = true
            }).catch((t) => {
                router.push({name: "unauthorized"})
                this.$err(err, '操作失败！')
            })
        }
        // 2.2 使用userId通过免密登录
        loading.value = false
        login(selectInstance.uerId).then(rsp => {
            let user = {
                id: rsp.data.userId,
                name: rsp.data.userName,
                avatar: rsp.data.avatar,
                position: rsp.data.position,
                type: 'user',
            }
            selectInstance.roles = rsp.data.roles[0].replace(/\"/g, "")
            localStorage.setItem('roles', JSON.stringify(selectInstance.roles))
            // this.$store.state.loginUser = user
            localStorage.setItem('loginUser', JSON.stringify(user))
            localStorage.setItem('wflow-token', rsp.data.token)
            selectInstance.processVisible = true
        })
    })
}
